﻿using System.Collections.Generic;
using System.Linq;
using TechnicalIndicators.Points;
using Utils;

namespace TechnicalIndicators.DateBased
{
    public class ExponentialAverage : GeneratorBase<DatedSeriePoint, DatedSeriePoint>
    {
        #region Attributes

        private int _valuesProcessed;
        private int _period;
        private decimal _exponent;
        private readonly List<decimal> _values;

        #endregion

        #region Public Methods

        public ExponentialAverage() : base()
        {
            _values = new List<decimal>();
        }

        public ExponentialAverage(ObservableCollection2<DatedSeriePoint> destination) : base(destination)
        {
            _values = new List<decimal>();
        }

        public void Configure(int samples)
        {
            _period = samples;
            _exponent = 2.0m / (_period + 1);
        }

        protected override DatedSeriePoint CreatePoint(DatedSeriePoint point)
        {
            DatedSeriePoint newPoint = null;

			_valuesProcessed++;

            if (_valuesProcessed > _period)
            {
                newPoint = new DatedSeriePoint(point.X, point.Y * _exponent + (base.LastValue.Y * (1 - _exponent)));
            }
            else if (_valuesProcessed == _period)
            {
				_values.Add(point.Y);
                newPoint = new DatedSeriePoint(point.X, _values.Sum() / _period);
				_values.Clear(); // The data is not needed anymore
            }
            else
            {
                _values.Add(point.Y);
            }

            return newPoint;
        }

        public override void Clear()
        {
            _values.Clear();
            _valuesProcessed = 0;
            base.Clear();
        }

        #endregion
    }
}
